#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <time.h>

using namespace std;

int main()
{
  //time between pictures (in seconds)
  double interval = 10; 
  
  //camera initilization time (seconds). some cameras take a few seconds 
  //to initialize before they're able to take a decent picture
  int cam_init = 2; 
  
  stringstream ss;
   
  //capture image using fswebcam after a delay of cam_init seconds
  //save image under /tmp
  ss << cam_init;
  string capture_command = string("fswebcam --delay ") + ss.str() + " --no-banner /tmp/relapse_pic.jpg";
  system( capture_command.c_str() );
  
  //convert image into short video 
  system ( "mencoder mf:///tmp/relapse_pic.jpg -mf fps=1:type=jpg -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o /tmp/relapse_short_video.avi" );
  
  //remove temporary files
  system( "rm /tmp/relapse_pic.jpg" );
  
  //move short video into current working directory. 
  //this will be first segment of main video file.
  system( "mv /tmp/relapse_short_video.avi ./relapse_video.avi");


/////////////////////////////////////////////////////////////////////////////////////////////////////////////

  
  int count = 1;
  while ( true )
  {
    time_t interval_start_time;
    interval_start_time = time(NULL);
    
    time_t interval_current_time;
    interval_current_time = time(NULL);
    
    //capture image using fswebcam after a delay of cam_init seconds
    //save image under /tmp
    ss.str("");
    ss << cam_init;
    string capture_command = string("fswebcam --delay ") + ss.str() + " --no-banner /tmp/relapse_pic.jpg";
    system( capture_command.c_str() );
 
    //convert image into short video 
    system ( "mencoder mf:///tmp/relapse_pic.jpg -mf fps=1:type=jpg -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o /tmp/relapse_short_video.avi" );
    
    //concatenate short video with main video in current directory
    system("mv ./relapse_video.avi ./relapse_cat_temp_video.avi");
    system("mencoder -ovc lavc ./relapse_cat_temp_video.avi /tmp/relapse_short_video.avi -o relapse_video.avi");
    
    ////remove temporary files
    system( "rm /tmp/relapse_short_video.avi" );
    system( "rm /tmp/relapse_pic.jpg" );
    system( "rm ./relapse_cat_temp_video.avi" );
    
    cout << "Video segments generated: " << count << endl;
    count = count + 1;
    
    while ( interval_current_time <= (interval_start_time + interval) )
    {
      interval_current_time = time(NULL);
    }
  }
  
  return 0;
}




